/*
c
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 55;
int n, m;
char grid[N][N];
bool st1[N][N];//用来标记陆地
bool st2[N][N]; //用来标记海
int dx1[4] = {-1, 0, 1, 0};
int dy1[4] = {0, 1, 0, -1};
int ret = 0;
int dx2[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy2[8] = {0, 1, 1, 1, 0, -1, -1, -1};

// 用来标记陆地
void bfs1(int x, int y)
{
    queue<pair<int, int>> qq;
    qq.push(make_pair(x, y));
    st1[x][y] = true;

    while (qq.size())
    {
        auto tem1 = qq.front();
        qq.pop();
        
        int cx = tem1.first;
        int cy = tem1.second;
        for (int i = 0; i < 4; i++)
        {
            int nx = cx + dx1[i] ;
            int ny = cy + dy1[i] ;
            if (nx >= 1 && nx <= m && ny >= 1 && ny <= n && !st1[nx][ny] && grid[nx][ny] == '1')
            {
                st1[nx][ny] = true;
                qq.push(make_pair(nx, ny));
            }
        }
    }
}
//用来标记海
void bfs2(int x,int y)
{
    queue<pair<int, int>> qq;
    qq.push(make_pair(x, y));
    st2[x][y] = true;
    
    while(qq.size())
    {
        auto tem1 = qq.front();
        qq.pop();
        int cx = tem1.first;
        int cy = tem1.second;
        for (int i = 0; i < 8; i++)
        {
            int nx = cx + dx2[i] ;
            int ny = cy + dy2[i] ;
            if (nx >= 0 && nx <= m+1&& ny >= 0 && ny <= n+1 )
            {
                //如果遇到岛屿还没被标记就去bfs1
                if(grid[nx][ny]=='1'&&!st1[nx][ny])
                {
                    bfs1(nx,ny);
                    ret++;
                }
                else
                {
                    //不是岛屿
                    if(!st2[nx][ny]&&grid[nx][ny]=='0')
                    {
                        //如果是海并且没有走过的海加入队列
                        qq.push(make_pair(nx,ny));
                        st2[nx][ny]=true;
                    }
                }
            }
        }
    }

}
void solve()
{
    memset(grid, '0', sizeof(grid));
    memset(st1, false, sizeof(st1));
    memset(st2, false, sizeof(st2));
    ret = 0;

    cin >> m >> n;
    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            cin >> grid[i][j];
        }
    }
    bfs2(0,0);//从外海搜如果遇到岛屿就开始bfs1把岛屿全部标记
    cout << ret << endl;
}

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        solve();
    }
}